/**
 * Created by zhouli on 18/1/30
 * Email li.zhou@huilianyi.com
 * 组织架构部门角色
 * 两种状态，编辑与非编辑
 */
import React from 'react';
import {connect} from 'react-redux';
import { messages} from "share/common";
import 'styles/enterprise-manage/org-structure/org-component/org-roles.scss';
import OrgService from 'containers/enterprise-manage/org-structure/org-structure.service';
import {
  Button, Icon, Menu, Dropdown, message, Popover, Input, Select, Form, Tooltip, TimePicker
} from 'antd';
import ListSelector from 'components/list-selector.js';
import chooserData from 'share/chooserData';
import {LanguageInput} from 'components/index';
import {fitText} from 'share/common';
import moment from 'moment';
import {ImageUpload} from 'components/index';

const FormItem = Form.Item;
const Option = Select.Option;
const {TextArea} = Input;

//点击取消时用
class OrgStructureRoles extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      selectedKeysDepDataByApi: {},
      editing: false,
      showListSelectorCompany: false,
      extraParamsCompany: {//弹窗额外的参数
      },
      selectorItemCompany: chooserData['department_connect_company'],//弹窗显示配置
      showListSelector: false,//弹窗是否显示
      extraParams: {//弹窗额外的参数
        excludeList: [],
        systemCustomEnumerationType: "" // systemCustomEnumerationType 代表类型，1001 type,1002 duty , 1008 级别
      },
      selectorItem: chooserData['user'],//弹窗显示配置
      currentRole: {},//当前被选中的角色
      codeClass: "f-left roles-title-text",
      codeDisabled: false,
    }
  }

  componentWillMount() {
    this.setState({selectedKeysDepDataByApi: this.props.selectedKeysDepDataByApi});
  }

  componentWillReceiveProps(nextProps) {
    this.setState({selectedKeysDepDataByApi: nextProps.selectedKeysDepDataByApi}, () => {
      let codeClass = "f-left roles-title-text";
      let codeDisabled = false;
      if (this.state.selectedKeysDepDataByApi.custDeptNumber) {
        codeClass = "f-left roles-title-text roles-title-text-disabled";
        codeDisabled = true;
      }
      this.setState({
        codeDisabled,
        codeClass
      })
    });
  }

  //处理条件添加弹框点击ok,添加值
  handleListOk = (result) => {
    const arr = result.result;
    let {currentRole} = this.state;
    currentRole.userOID = arr[0].userOID;
    currentRole.userName = arr[0].fullName;
    this.setCurrentRoleToOriginDep(currentRole);
    //关闭弹窗
    this.handleCancel();
  };
  //处理条件添加弹框点击ok,添加值
  handleListOkCompany = (result) => {
    const arr = result.result;
    let {selectedKeysDepDataByApi} = this.state;
    selectedKeysDepDataByApi._companyOID = arr[0].companyOID;
    selectedKeysDepDataByApi.companyName = arr[0].name;
    this.setState({
      selectedKeysDepDataByApi
    });
    //关闭弹窗
    this.handleCancelCompany();
  };
  //把选中的角色还原
  setCurrentRoleToOriginDep = (role) => {
    let {selectedKeysDepDataByApi} = this.state;
    for (let i = 0; i < selectedKeysDepDataByApi.length; i++) {
      if (selectedKeysDepDataByApi[i].id === role.id) {
        selectedKeysDepDataByApi[i] = role;
      }
    }
    this.setState({selectedKeysDepDataByApi});
  }
  //控制是否弹出条件添加弹窗
  handleCancel = () => {
    this.setState({showListSelector: false, saving: false})
  };
  handleCancelCompany  = () => {
    this.setState({showListSelectorCompany: false})
  };
  //添加公司
  selectCompany = () => {
    const {extraParamsCompany} = this.state;
    this.setState({showListSelectorCompany: true,extraParamsCompany});
  };
  //添加人员
  selectRoleUser = (role) => {
    this.setState({
      currentRole: role
    })
    this.setState({showListSelector: true});
  };
  //移除公司，这个要加逻辑，是 OPEN 情况不能删除
  removeCompany = () => {
    let {selectedKeysDepDataByApi} = this.state;
    selectedKeysDepDataByApi._companyOID = "";
    selectedKeysDepDataByApi.companyName = "";
    this.setState({
      selectedKeysDepDataByApi
    })
  };
  //移除角色
  removeRoleUser = (item) => {
    item.userOID = "";
    item.userName = "";
    this.setCurrentRoleToOriginDep(item);
  };
  editRoles = () => {
    let {selectedKeysDepDataByApi} = this.state;
    let codeClass = "f-left roles-title-text";
    let codeDisabled = false;
    if (selectedKeysDepDataByApi.custDeptNumber) {
      codeClass = "f-left roles-title-text roles-title-text-disabled";
      codeDisabled = true;
    }
    this.setState({
      editing: true,
      codeDisabled,
      codeClass
    }, () => {
      this.props.emitIsEdit(this.state.editing)
    })
  };
  cancelRoleHandle = () => {
    this.setState({
      editing: false,
    }, () => {
      this.props.emitIsEdit(this.state.editing, this.state.selectedKeysDepDataByApi)
    })
  };
  checkManagerIsOk = () => {
    if (this.props.managerIsRequired) {
      let roleList = this.state.selectedKeysDepDataByApi.departmentPositionDTOList;
      for (let i = 0; i < roleList.length; i++) {
        if (roleList[i].positionCode === "6101") {
          if (roleList[i].userOID === null ||
            roleList[i].userOID === "" ||
            roleList[i].userOID === undefined) {
            return false
          }
        }
      }
      return true;
    } else {
      return true;
    }
  }
  // 这里借用人员扩展字段
  // 把表单的值设置到人员信息扩展字段里面去
  setFromToCustomFormValues = (values) => {
    let customFormValues = this.state.selectedKeysDepDataByApi.customFormValues;
    if (customFormValues) {
      for (let key in values) {
        for (let i = 0; i < customFormValues.length; i++) {
          if (customFormValues[i].fieldOID === key) {
            if (customFormValues[i].messageKey === "common.date") {
              customFormValues[i].value = values[key] ? new Date(moment(values[key]).format("YYYY-MM-DD")) : "";
            } else if (customFormValues[i].messageKey === "time") {
              if (values[key]) {
                customFormValues[i].value = moment(values[key]).format("HH:mm");
              } else {
                customFormValues[i].value = "";
              }
            } else if (customFormValues[i].messageKey === "image") {
              //把attachmentImages赋值，只是为了前端展示
              customFormValues[i].attachmentImages = values[key];
              //这个地方要注意一下 服务端返回的图片字段是attachmentImages
              //但是上传的时候是attachments
              customFormValues[i].attachments = values[key];
              //还需要把value设置一下
              if (customFormValues[i].attachments) {
                let _values = [];
                for (let j = 0; j < customFormValues[i].attachments.length; j++) {
                  _values.push(customFormValues[i].attachments[j].attachmentOID);
                }
                customFormValues[i].value = JSON.stringify(_values);
              }
            } else {
              let t = this.getValueByMessageKey(values, key, customFormValues);
              customFormValues[i].value = t ? t : values[key];
            }
          }
        }
      }
    }
  }
  /*
  * fixd bug 33923
  * 扩展字段点击修改，不选择值列表，直接保存，antd 会把显示的值(messageKey)当做真正的值(value)
  * 需要用 messageKey 去匹配真正的值
  * */
  getValueByMessageKey = (values, key, customFormValues) => {
    for(let i = 0; i < customFormValues.length; i++){
      if(customFormValues[i].fieldOID === key){
        if(customFormValues[i].messageKey === "cust_list" &&
          customFormValues[i].customEnumerationList &&
          customFormValues[i].customEnumerationList.values &&
          customFormValues[i].customEnumerationList.values.length
        ){
          let list = customFormValues[i].customEnumerationList.values;
          for(let i = 0; i < list.length; i++){
            if(list[i].messageKey === values[key]){
              return list[i].value;
            }
          }
        }
      }
    }
  }
  confirmRoleHandle = () => {
    let {selectedKeysDepDataByApi} = this.state;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        if(!selectedKeysDepDataByApi.companyOID && selectedKeysDepDataByApi._companyOID){
          selectedKeysDepDataByApi.companyOID = selectedKeysDepDataByApi._companyOID
        }
        this.setFromToCustomFormValues(values);
        if (this.checkManagerIsOk()) {
          this.setState({
            loading: true
          });

          OrgService.updateDep(selectedKeysDepDataByApi)
            .then((res) => {
              let dep = this.state.selectedKeysDepDataByApi;
              dep.custDeptNumber = res.data.custDeptNumber;
              this.props.updateDepSuccess();
              this.setState({
                selectedKeysDepDataByApi: dep,
                editing: false,
                loading: false
              }, () => {
                this.props.emitIsEdit(this.state.editing)
              })
            })
            .catch((res) => {
              let codeClass = "f-left roles-title-text";
              this.setState({
                codeDisabled: false,
                loading: false,
                codeClass
              });
            })
        } else {
          message.error(messages('enterprise-manage.key149'/*请填写部门经理*/))
        }
      }
    });
  };
  //停用该部门
  disabledDep = () => {
    this.props.disabledDep(this.state.selectedKeysDepDataByApi);
  }
  //创建子部门
  createChildDep = (e) => {
    this.props.clickMeunNewChildDep(e, this.props.selectedKeysDepData)
  }
  //组织架构部门详情菜单
  renderRoleMoreMeun = () => {
    return (
      <Menu>
        <Menu.Item key="0">
          <div onClick={() => {
            this.editRoles();
          }}>
            {messages('enterprise-manage.key150'/*编辑*/)}
          </div>
        </Menu.Item>
        <Menu.Item key="1">
          <div onClick={(event) => {
            this.disabledDep()
          }}>
            {messages('enterprise-manage.key151'/*停用该部门*/)}
          </div>
        </Menu.Item>

        <Menu.Item key="2">
          <div onClick={(event) => {
            this.createChildDep(event)
          }}>
            {messages('enterprise-manage.key152'/*创建子部门*/)}
          </div>
        </Menu.Item>
      </Menu>
    )
  }
  renderExtendFiled = () => {
    let dep = this.state.selectedKeysDepDataByApi;
    let values = dep.customFormValues ? dep.customFormValues : [];
    return <div className="extend-field-no-edit-wrap">
      <div className="extend-field-title"> {messages('enterprise-manage.key153'/*扩展字段*/)}
        &nbsp;&nbsp;<Tooltip title={messages('enterprise-manage.key154'/*可在组织架构-部门扩展字段进行编辑部门扩展字段*/)}>
          <Icon type="question-circle-o"/>
        </Tooltip>
      </div>
      <div className="extend-field-list-wrap">
        {this.renderNoEditingForExtend()}
      </div>
    </div>
  }

  //渲染非编辑状态
  renderNoEditingForExtend = () => {
    let dep = this.state.selectedKeysDepDataByApi;
    let values = dep.customFormValues ? dep.customFormValues : [];

    let dom = [];
    for (let i = 0; i < values.length; i++) {
      dom.push(this.renderContentByMessageKey(values[i]))
    }
    return (
      <div>
        {dom}
        <div className="clear"/>
      </div>
    )
  };
  // -----扩展字段-非编辑状态---start
  //目前这边只有自定义列表类型，cust_list
  renderContentByMessageKey = (field) => {
    let messageKey = field.messageKey;
    //分为：单行输入框，多行输入框，值列表，日期，数字，时间，图片
    switch (messageKey) {
      case "input": {
        return this.renderFiled_input(field);
        break;
      }
      case "text_area": {
        return this.renderFiled_text_area(field);
        break;
      }
      case "cust_list": {
        return this.renderFiled_cust_list(field);
        break;
      }
      case "date": {
        return this.renderFiled_date(field);
        break;
      }
      case "common.date": {
        return this.renderFiled_date(field);
        break;
      }
      case "number": {
        return this.renderFiled_number(field);
        break;
      }
      case "time": {
        return this.renderFiled_time(field);
        break;
      }
      case "image": {
        return this.renderFiled_image(field);
        break;
      }
    }
  }

  renderFiled_input = (field) => {
    let messageKey = field.messageKey;
    //后端可能返回的是值列表值对应的code（value），不是messageKey，需要找一下
    //参见bug13014
    if (messageKey === "cust_list" &&
      field.customEnumerationList &&
      field.customEnumerationList.values &&
      field.customEnumerationList.values.length &&
      field.customEnumerationList.values.length > 0) {
      let customEnumerationList = field.customEnumerationList.values;
      for (let i = 0; i < customEnumerationList.length; i++) {
        if (field.value === customEnumerationList[i].value) {
          field.value = customEnumerationList[i].messageKey;
        }
      }
    }
    return (
      <div className="info-item f-left" key={field.fieldOID}>
        <div className="info-item-title">{this.renderNoEditingText(field.fieldName, 10)}:</div>
        <div className="info-item-text">
          {this.renderNoEditingText(field.value, 10)}
        </div>
        <div className="clear"/>
      </div>
    )
  }
  renderFiled_text_area = (field) => {
    return this.renderFiled_input(field);
  }
  renderFiled_cust_list = (field) => {
    return this.renderFiled_input(field);
  }
  renderFiled_date = (field) => {
    let date = field.value ? (new Date(field.value)).format("yyyy-MM-dd") : "";
    return (
      <div className="info-item f-left" key={field.fieldOID}>
        <div className="info-item-title">{field.fieldName}：</div>
        <div className="info-item-text">{date}</div>
      </div>
    )
  }
  renderFiled_number = (field) => {
    field.unit = "";
    if (field.fieldContent) {
      let content = {};
      try {
        content = JSON.parse(field.fieldContent);
        field.unit = content.unit;
      }
      catch (e) {
      }
    }
    return (
      <div className="info-item f-left" key={field.fieldOID}>
        <div className="info-item-title">{field.fieldName}：</div>
        <div className="info-item-text">{field.value}&nbsp;{field.value ? field.unit : ""}</div>
      </div>
    )
  }
  renderFiled_time = (field) => {
    let val = moment(field.value, 'HH:mm').format("HH:mm");
    if (field.value === null || field.value === "") {
      val = "";
    }
    if (field.value && field.value.length > 5) {
      //兼容以前的
      val = moment(field.value).format("HH:mm");
    }
    return (
      <div className="info-item f-left" key={field.fieldOID}>
        <div className="info-item-title">{field.fieldName}：</div>
        <div className="info-item-text">{val}</div>
      </div>
    )
  }
  renderFiled_image = (field) => {
    //可能需要渲染多张图片（1-3张）
    function _getTooltipImages(imgs) {
      let imgsDom = [];
      if (imgs && imgs.length > 0) {
        imgs.map((item) => {
          imgsDom.push(
            <Tooltip title={
              <img className="info-item-img-tip"
                   src={item.thumbnailUrl}/>
            }>
              <img src={item.thumbnailUrl}/>
            </Tooltip>
          )
        })
        return imgsDom;
      } else {
        return (
          <div/>
        );
      }
    }

    return (
      <div className="info-item f-left" key={field.fieldOID}>
        <div className="info-item-title">{field.fieldName}：</div>
        <div className="info-item-text">
          {_getTooltipImages(field.attachmentImages)}
        </div>
      </div>
    )
  }
  // -----扩展字段-非编辑状态---end
  renderExtendFiledEditing = () => {
    let dep = this.state.selectedKeysDepDataByApi;
    let values = dep.customFormValues ? dep.customFormValues : [];
    return <div className="extend-field-edit-wrap">
      <div className="extend-field-title">{messages('enterprise-manage.key153'/*扩展字段*/)}
        &nbsp;&nbsp;<Tooltip title={messages('enterprise-manage.key154'/*可在组织架构-部门扩展字段进行编辑部门扩展字段*/)}>
          <Icon type="question-circle-o"/>
        </Tooltip></div>
      <div>
        {this.renderEditingField(values)}
      </div>
    </div>
  }
  // -----扩展字段 编辑状态---start
  renderEditingField = (values) => {
    let dom = [];
    for (let i = 0; i < values.length; i++) {
      dom.push(this.renderEditingContentByMessageKey(values[i]))
    }
    return dom;
  }
  renderEditingContentByMessageKey = (field) => {
    let messageKey = field.messageKey;
    //分为：单行输入框，多行输入框，值列表，日期，数字，时间，图片
    switch (messageKey) {
      case "input": {
        return this.renderEditingFiled_input(field);
        break;
      }
      case "text_area": {
        return this.renderEditingFiled_text_area(field);
        break;
      }
      case "cust_list": {
        return this.renderEditingFiled_cust_list(field);
        break;
      }
      case "date": {
        return this.renderEditingFiled_date(field);
        break;
      }
      case "common.date": {
        return this.renderEditingFiled_date(field);
        break;
      }
      case "number": {
        return this.renderEditingFiled_number(field);
        break;
      }
      case "time": {
        return this.renderEditingFiled_time(field);
        break;
      }
      case "image": {
        return this.renderEditingFiled_image(field);
        break;
      }
    }
  }
  renderEditingFiled_input = (field) => {
    const {getFieldDecorator} = this.props.form;
    return (
      <FormItem
        key={field.fieldOID}
        label={field.fieldName}
        colon={true}>
        {getFieldDecorator(field.fieldOID, {
          initialValue: field.value,
          rules: [
            {
              max: 50,
              message: messages('enterprise-manage.key155'/*最多输入50个字符*/)
            },
            {
              required: field.required,
              message: messages('common.please.enter')
            }
          ]
        })(
          <Input placeholder={messages('common.please.enter')}/>)
        }
      </FormItem>
    )
  }
  renderEditingFiled_text_area = (field) => {
    const {getFieldDecorator} = this.props.form;

    return (
      <FormItem
        key={field.fieldOID}
        label={field.fieldName}
        colon={true}>
        {getFieldDecorator(field.fieldOID, {
          initialValue: field.value,
          rules: [
            {
              max: 200,
              message: messages('enterprise-manage.key156'/*最多输入200个字符*/)
            },
            {
              required: field.required,
              message: messages('common.please.enter')
            }
          ]
        })(
          <TextArea placeholder={messages('common.please.enter')}/>)
        }
      </FormItem>
    )
  }
  renderEditingFiled_cust_list = (field) => {
    const {getFieldDecorator} = this.props.form;
    //如果是值列表类型，在返回的数据上，前端多挂了一个customEnumerationList属性，
    //这个选择列表就从这个属性上拿了
    return (
      <FormItem
        key={field.fieldOID}
        label={field.fieldName}
        colon={true}>
        {getFieldDecorator(field.fieldOID, {
          initialValue: field.value,
          rules: [
            {
              required: field.required,
              message: messages('common.please.enter')
            }
          ]
        })(
          <Select>
            {field.customEnumerationList && _renderCustomEnumerationList(field.customEnumerationList.values)}
          </Select>
        )
        }
      </FormItem>
    )

    //渲染值列表
    function _renderCustomEnumerationList(list) {
      let dom = [];
      if (list.length > 0) {
        list.map(function (item) {
          /*
           * 要做多语言，这个地方上传 code，后端返回的时候，任然是 messageKey，所以显示的时候用 messageKey 去查 value 显示
           * code 值可以是 null，所以传 value，值列表的 value 就是 code
           * 之前上传的是 messageKey
           * dom.push(<Option key={item.id} value={item.messageKey}>{item.messageKey}</Option>)
           * */
          dom.push(<Option key={item.id} value={item.value}>{item.messageKey}</Option>)
        })
        return dom;
      } else {
        return ("");
      }
    }
  }
  renderEditingFiled_date = (field) => {
    const {getFieldDecorator} = this.props.form;
    let val = field.value ? moment(field.value).format("YYYY-MM-DD") : new Date();
    return (
      <FormItem
        key={field.fieldOID}
        label={field.fieldName}
        colon={true}>
        {getFieldDecorator(field.fieldOID, {
          initialValue: moment(val, 'YYYY-MM-DD'),
          rules: [
            {
              required: field.required,
              message: messages('common.please.enter')
            }
          ]
        })(
          <DatePicker format={'YYYY-MM-DD'}/>
        )
        }
      </FormItem>
    )
  }
  renderEditingFiled_number = (field) => {
    const {getFieldDecorator} = this.props.form;
    field.unit = null;
    if (field.fieldContent) {
      let content = {};
      try {
        content = JSON.parse(field.fieldContent);
        field.unit = content.unit;
        if (field.unit && field.unit.length > 0) {
          field.unit = "(" + field.unit + ")";
        } else {
          field.unit = "";
        }
      }
      catch (e) {
      }
    }
    // 要根据限制条件进行校验
    let fieldConstraint = {
      integerMaxLength: "",
      decimalMaxLength: "",
    }
    if (field.fieldConstraint) {
      let _fieldConstraint = {};
      try {
        _fieldConstraint = JSON.parse(field.fieldConstraint);
        fieldConstraint.integerMaxLength = _fieldConstraint.integerMaxLength;
        fieldConstraint.decimalMaxLength = _fieldConstraint.decimalMaxLength;
        field._fieldConstraint = fieldConstraint;
      }
      catch (e) {
      }
    }
    return (
      <FormItem
        key={field.fieldOID}
        label={field.fieldName + field.unit}
        colon={true}>
        {getFieldDecorator(field.fieldOID, {
          initialValue: field.value,
          rules: [
            {
              required: field.required,
              message: messages('common.please.enter')
            },
            {
              message: messages('enterprise-manage.key157'/*整数位数最多*/) + fieldConstraint.integerMaxLength + "," +
              messages('enterprise-manage.key158'/*小数位最多*/) + fieldConstraint.decimalMaxLength,
              validator: (fieldConstraint, value, cb) => {
                //必须是必填的才有校验
                if (field.fieldConstraint && field.required && value) {
                  let fieldConstraint = field._fieldConstraint;
                  if ((value.split(".")[0].length > fieldConstraint.integerMaxLength) ||
                    (value.split(".")[1] && value.split(".")[1].length > fieldConstraint.decimalMaxLength)) {
                    cb(false);
                    return;
                  } else {
                    cb();
                  }
                } else {
                  cb();
                }
              },
            }
          ]
        })(<Input type="number" placeholder={messages('common.please.enter')}/>)
        }
      </FormItem>
    )
  }
  onChangeTime = (time) => {
  }
  renderEditingFiled_time = (field) => {
    const {getFieldDecorator} = this.props.form;
    //这个 field.value 就直接显示，正式环境没有这种数据
    //其他环境不管
    let val = moment(field.value, 'HH:mm');
    if (field.value === null || field.value === "") {
      val = "";
    }
    if (field.value && field.value.length > 5) {
      //兼容以前的
      val = moment(field.value).format("HH:mm");
      val = moment(val, 'HH:mm');
    }
    return (
      <FormItem
        key={field.fieldOID}
        label={field.fieldName}
        colon={true}>
        {getFieldDecorator(field.fieldOID, {
          initialValue: val,
          rules: [
            {
              required: field.required,
              message: messages('common.please.enter')
            }
          ]
        })(
          <TimePicker onChange={this.onChangeTime}
                      format={"HH:mm"}/>
        )
        }
      </FormItem>
    )
  }
  renderEditingFiled_image = (field) => {
    const {getFieldDecorator} = this.props.form;
    //上传之后，图片对象直接就绑定到field.attachmentImages里面了
    const fileList = field.attachmentImages;
    return (
      <FormItem
        key={field.fieldOID}
        label={field.fieldName}
        colon={true}>
        {getFieldDecorator(field.fieldOID, {
          initialValue: fileList,
          rules: [
            {required: field.required, message: messages('common.please.enter')}
          ]
        })(
          <ImageUpload attachmentType="INVOICE_IMAGES"
                       fileType={["PNG", 'png', 'jpeg', 'jpeg', 'jpg', 'JPG', 'bmp', 'BMP']}
                       defaultFileList={fileList}
                       isShowDefault={true}
                       maxNum={field.fieldConstraint ? JSON.parse(field.fieldConstraint).maxNumber : 9}/>
        )
        }
      </FormItem>
    )
  }
  // -----扩展字段 编辑状态---end
  //渲染角色
  renderRole = (roles) => {
    if (roles && roles.length > 0) {
      return roles.map((item) => {
        return <div key={item.id} className="role-item">
          <div className="role-item-position">{item.positionName}:</div>
          <div className="role-item-user">{item.userName}</div>
          <div className="clear"/>
        </div>
      })
    } else {
      return <div/>
    }
  }
  renderCompanyEditing = (selectedKeysDepDataByApi) => {
    //是否可以可以修改
    let isCanUpdate = true;
    let className = "role-item";
    // 为 INIT
    // 为 CLOSE 且没有值
    // 为 OPEN 是肯定有值不能修改的
    if(selectedKeysDepDataByApi.companyOID) {
      isCanUpdate = false;
    }
    className = isCanUpdate ? "role-item" : "role-item role-item-disabled";
    return <div key="-1" className={className}>
      <div className="role-item-position">{messages('enterprise-manage.key76')/*公司名称*/}:</div>
      <div className="role-item-user">
        {/*请选择的节点需要重新渲染加className*/}
        {/*选择公司和删除公司以前有限制，isCanUpdate为true才可以选择，现在去掉了*/}
        <div className="f-left user-name"
             onClick={() => {isCanUpdate && this.selectCompany()}}>{selectedKeysDepDataByApi.companyName} </div>
        {isCanUpdate && <div className="f-right remove" onClick={() => {this.removeCompany()}}>
          <Icon type="close"/>
        </div>}
      </div>
      <div className="clear"/>
    </div>
  }
  //渲染编辑状态角色
  renderRoleEditing = (roles) => {
    if (roles && roles.length > 0) {
      return roles.map((item) => {
        return <div key={item.id} className="role-item">
          <div className="role-item-position">{item.positionName}:</div>
          <div className="role-item-user">
            {/*请选择的节点需要重新渲染加className*/}
            <div className="f-left user-name"
                 onClick={() => {
                   this.selectRoleUser(item)
                 }}>{this.renderRoleEditingUserName(item)} </div>
            <div className="f-right remove" onClick={() => {
              this.removeRoleUser(item)
            }}><Icon type="close"/></div>
          </div>
          <div className="clear"/>
        </div>
      })
    } else {
      return <div/>
    }
  }
  renderRoleEditingUserName = (item) => {
    if (item.userName) {
      return <div>{item.userName}</div>
    } else {
      return <div className='please-select'>
        {messages('enterprise-manage.key159'/*请选择*/)}
      </div>
    }
  }

  i18nChange = (name, i18nName) => {
    let {selectedKeysDepDataByApi} = this.state;
    selectedKeysDepDataByApi.name = name;
    selectedKeysDepDataByApi.i18n = {
      name: i18nName
    };
    this.setState({
      selectedKeysDepDataByApi
    });

  }
  depCustDeptNumberChange = (e) => {
    let {selectedKeysDepDataByApi} = this.state;
    let code = e.target.value;
    code = code.replace(/\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g, "");
    selectedKeysDepDataByApi.custDeptNumber = code;
    this.setState({
      selectedKeysDepDataByApi
    });
  }
  renderRoleMoreMeunByRole = () => {
    let {selectedKeysDepDataByApi} = this.state;
    if (selectedKeysDepDataByApi.status + "" !== "101") {
      return <span/>;
    }
    if (this.props.ROLE_TENANT_ADMIN && this.props.CREATE_DATA_TYPE) {
      return (
        <div style={{position : "absolute", right: 20, top: 20}}>
          <Dropdown overlay={
            this.renderRoleMoreMeun()
          } trigger={['click']}>
            <a className="ant-dropdown-link" href="#">
              <Icon type="setting"/>
            </a>
          </Dropdown>
        </div>
      )
    } else {
      return (
        <div/>
      )
    }
  }
  //渲染字段的内容，根据情况进行截取，鼠标浮动有提示
  renderNoEditingText = (text, len) => {
    let _len = len || 13;
    let _text = fitText(text, _len);
    if (_text.text) {
      return (
        <Popover placement="topLeft" content={_text.origin} overlayStyle={{maxWidth: 500}}>
          <span>{_text.text}...</span>
        </Popover>
      )
    } else {
      return (text)
    }
  }

  render() {
    let {selectedKeysDepDataByApi} = this.state;
    let rolesWrap = '';
    let rolesTitleWrap = '';
    let extendFiledWrap = '';
    if (this.state.editing) {
      rolesTitleWrap = <div>
        <div className="roles-code-wrap">
          <div className="f-left roles-title">
            {messages('enterprise-manage.key161'/*部门编码*/)}：
          </div>
          <div className="f-left roles-title-text">
            <Input className={this.state.codeClass}
                   key={'custDeptNumber'}
                   id='code-input'
                   disabled={this.state.codeDisabled}
                   onChange={this.depCustDeptNumberChange}
                   value={selectedKeysDepDataByApi.custDeptNumber ? selectedKeysDepDataByApi.custDeptNumber : ""}
                   placeholder={messages('enterprise-manage.key162'/*请输入*/)}
            />
          </div>
        </div>
        <div className="clear"/>

        <div>
          <div className="f-left roles-title">
            <span className="red-star">*</span> {messages('enterprise-manage.key160'/*部门名称*/)}：
          </div>
          <div className="f-left roles-title-text">
            <LanguageInput
              name={selectedKeysDepDataByApi.name}
              i18nName={selectedKeysDepDataByApi.i18n.name}
              isEdit={true}
              nameChange={this.i18nChange}
            />
          </div>
        </div>

        <div className="clear"/>

        <div className="roles-wrap-editing">
          {this.renderCompanyEditing(selectedKeysDepDataByApi)}
        </div>
      </div>;
      rolesWrap = <div className="roles-wrap-editing">
        {this.renderRoleEditing(selectedKeysDepDataByApi.departmentPositionDTOList)}
        <div className="clear"/>
      </div>
      extendFiledWrap = <div className="extend-field-wrap">
        {this.renderExtendFiledEditing()}
        <div className="clear"/>
        <div className="btn-wrap">
          <Button type="primary"
                  loading={this.state.loading}
                  onClick={this.confirmRoleHandle}>
            {messages('common.save') /*保存*/}
          </Button>
          <Button onClick={this.cancelRoleHandle}>
            {messages('common.cancel') /*取消*/}
          </Button>
        </div>
      </div>

    } else {
      rolesTitleWrap = <div>
        {selectedKeysDepDataByApi.status + "" !== "101" && <div className='inactive-date-wrap'>
          <span>{messages('enterprise-manage.key341')/*失效时间:*/}</span>&nbsp;&nbsp;
          <span>{selectedKeysDepDataByApi.inactiveDate && moment(selectedKeysDepDataByApi.inactiveDate).format("YYYY-MM-DD HH:mm")}</span>
        </div>}

        <div className="roles-code-wrap1">
          <div className="f-left roles-title">
            {messages('enterprise-manage.key161'/*部门编码*/)}
          </div>

          <div className="f-left roles-title-text">
            {this.renderNoEditingText(selectedKeysDepDataByApi.custDeptNumber)}
          </div>
        </div>
        <div className="clear"/>
        <div>
          <div className="f-left roles-title">
            {messages('enterprise-manage.key160'/*部门名称*/)}
          </div>

          <div className="f-left roles-title-text">
            {this.renderNoEditingText(selectedKeysDepDataByApi.name)}
          </div>
        </div>

        <div className="clear"/>
        {selectedKeysDepDataByApi.companyName && <div> {messages('enterprise-manage.key76')/*公司名称*/}：{selectedKeysDepDataByApi.companyName}
        </div>}
      </div>;
      rolesWrap = <div className="roles-wrap">
        {this.renderRole(selectedKeysDepDataByApi.departmentPositionDTOList)}
        <div className="clear"/>
      </div>
      extendFiledWrap = <div className="extend-field-wrap">
        {this.renderExtendFiled()}
      </div>
    }
    return (
      <div className="org-structure-roles">
        <div className="roles-title-wrap">
          {rolesTitleWrap}
          <div className="f-right">
            {this.renderRoleMoreMeunByRole()}
          </div>
          <div className="clear"/>
        </div>
        {rolesWrap}
        {extendFiledWrap}
        <ListSelector
          single={true}
          visible={this.state.showListSelector}
          onOk={this.handleListOk}
          onCancel={this.handleCancel}
          extraParams={this.state.extraParams}
          selectorItem={this.state.selectorItem}
        />
        <ListSelector
          single={true}
          visible={this.state.showListSelectorCompany}
          onOk={this.handleListOkCompany}
          onCancel={this.handleCancelCompany}
          extraParams={this.state.extraParamsCompany}
          selectorItem={this.state.selectorItemCompany}
        />
      </div>
    )
  }
}

OrgStructureRoles.propTypes = {
  ROLE_TENANT_ADMIN: React.PropTypes.bool,
  CREATE_DATA_TYPE: React.PropTypes.bool,
  emitIsEdit: React.PropTypes.func.isRequired,//改变编辑状态的回调
  managerIsRequired: React.PropTypes.bool,//部门经理是否必填
  clickMeunNewChildDep: React.PropTypes.func,//点击创建子部门的回调
  disabledDep: React.PropTypes.func,//点击禁用的回调
  updateDepSuccess: React.PropTypes.func,//修改成功的
  selectedKeysDepDataByApi: React.PropTypes.object.isRequired,//被选择了的部门数据通过api
  selectedKeysDepData: React.PropTypes.object.isRequired,//被选择了的部门数据
  selectedKeys: React.PropTypes.array.isRequired,//被选择了的部门
};

function mapStateToProps(state) {
  return {
    isOldCompany: state.login.isOldCompany,
  }
}

const WrappedOrgStructureRoles = Form.create()(OrgStructureRoles);
export default connect(mapStateToProps)(WrappedOrgStructureRoles);
